package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.adapter.ManagerDeviceAdapter;
import com.qiantu.phone.ui.dialog.BottomDeviceFilterDialog;
import com.qiantu.phone.utils.DataHolder;
import com.lxj.xpopup.XPopup;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * time   : 2021/12/22
 */
public final class     SelectDeviceActivity extends AppActivity {

    public static final int TYPE_SELECT_TRIGGER_DEVICE = 1;
    public static final int TYPE_SELECT_DEVICE_SHARE = 2;
    public static final int TYPE_SELECT_SAME_DEVICE = 3;
    public static final int TYPE_PANEL_DEVICE = 4;
    public static final int TYPE_SELECT_TRIGGER_DEVICE_NEW = 5;

    private RecyclerView mRecyclerView;
//    private TextView selectArea;
//    private CheckBox checkbox;
    private View btnFilter;
    private View btnAllChoose;
    private EditText mEditSearch;
    private ManagerDeviceAdapter mManagerDeviceAdapter;
    //1选择触发设备 2选择分享设备
    private int type;
    private String deviceType;
    private String removeDeviceSerialNo;
    private List<DeviceBean> allDevices;
    private Boolean showAllSelect = false;
    private Boolean isAllSelect = false;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_select_device;
    }

    @Override
    protected void initView() {
        type = getInt("type");
        showAllSelect = getBoolean("showAllSelect");
        deviceType = getString("deviceType");
        removeDeviceSerialNo = getString("baseDevice");
//        selectArea = findViewById(R.id.select_area);
//        checkbox = findViewById(R.id.checkbox);
        mRecyclerView = findViewById(R.id.recycler_view);
        setOnClickListener(R.id.btn_filter,R.id.btn_all_choose);
        mEditSearch = findViewById(R.id.edit_search);
        btnAllChoose = findViewById(R.id.btn_all_choose);
        btnFilter = findViewById(R.id.btn_filter);
        btnAllChoose.setVisibility(showAllSelect ? View.VISIBLE : View.GONE);
        mEditSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(s.length() > 0){
                    searchDevice(s.toString());
                }else{
                    if(mBottomDeviceFilterDialog == null){
                        initData();
                    }else{
                        loadSelectedDevices();
                    }
                }
            }
        });
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mManagerDeviceAdapter = new ManagerDeviceAdapter(this);
        mManagerDeviceAdapter.setSubClickListener(createSubClickListener());
        mManagerDeviceAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                DeviceBean device = mManagerDeviceAdapter.getData().get(position);
                Intent intent = null;
                switch (type){
                    case TYPE_SELECT_TRIGGER_DEVICE:
                    case TYPE_SELECT_TRIGGER_DEVICE_NEW:
                        intent = new Intent(getContext(), SelectDeviceStatusActivity.class);
                        intent.putExtra("device_serial_no", device.getDeviceSerialNo());
                        intent.putExtra("isNewVersion",type == TYPE_SELECT_TRIGGER_DEVICE_NEW);
                        startActivity(intent);
                        break;
                    case TYPE_PANEL_DEVICE:
                        intent = new Intent(getContext(), LinkagePanelActivity.class);
                        intent.putExtra("device_serial_no", device.getDeviceSerialNo());
                        startActivity(intent);
                        break;
                }
            }
        });
        mRecyclerView.setAdapter(mManagerDeviceAdapter);
        switch (type){
            case TYPE_SELECT_TRIGGER_DEVICE:
            case TYPE_PANEL_DEVICE:
            case TYPE_SELECT_TRIGGER_DEVICE_NEW:
//                checkbox.setVisibility(View.GONE);
                setTitle(R.string.select_device);
                setRightTitle(null);
                mManagerDeviceAdapter.setSelectable(false);
                break;
            case TYPE_SELECT_DEVICE_SHARE:
//                checkbox.setVisibility(View.VISIBLE);
                setTitle(R.string.device_share_select);
                setRightTitle(R.string.save);
                mManagerDeviceAdapter.setSelectable(true);
                break;
            case TYPE_SELECT_SAME_DEVICE:
                setTitle("批量添加");
                setRightTitle(R.string.save);
                mManagerDeviceAdapter.setSelectable(true);
                List<DeviceBean> devices = (List<DeviceBean>) DataHolder.getInstance().getData("scene_same_device");
                mManagerDeviceAdapter.setSelected(devices);
                break;
            default:
//                checkbox.setVisibility(View.VISIBLE);
                setTitle(R.string.select_device);
                setRightTitle(R.string.save);
                mManagerDeviceAdapter.setSelectable(true);
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_filter:
//                showSelectAreaDialog(view);
                showBottomDeviceFilterDialog();
                break;
            case R.id.btn_all_choose:
//                showSelectAreaDialog(view);
                touchAllSelectButton();
                break;
//            case R.id.checkbox:
//                mManagerDeviceAdapter.setOnlySeeCommonly(checkbox.isChecked());
//                String text = (String) selectArea.getText();
//                selectArea.setText(text.split(" ")[0] + " (" + mManagerDeviceAdapter.getItemCount() + ")");
//                break;
        }
    }

    public void touchAllSelectButton(){
        isAllSelect = !isAllSelect;
        mManagerDeviceAdapter.setAllSelect(isAllSelect);
        btnAllChoose.setSelected(isAllSelect);
    }

    @Override
    public void onRightClick(View view) {
        List<DeviceBean> selectedDevices = mManagerDeviceAdapter.getSelectedData();
        DataHolder.getInstance().setData("scene_same_device", selectedDevices);
        setResult(RESULT_OK);
        finish();
    }


    private BottomDeviceFilterDialog mBottomDeviceFilterDialog;
    private void showBottomDeviceFilterDialog() {
        if (mBottomDeviceFilterDialog == null) {
            int deviceCategory = 0;
            switch (type){
                case TYPE_SELECT_TRIGGER_DEVICE:
                case TYPE_PANEL_DEVICE:
                case TYPE_SELECT_TRIGGER_DEVICE_NEW:
                    deviceCategory = BottomDeviceFilterDialog.TRIGGER_DEVICE;
                    break;
                case TYPE_SELECT_DEVICE_SHARE:
                case TYPE_SELECT_SAME_DEVICE:
                default:
                    deviceCategory = BottomDeviceFilterDialog.AVAILABLE_DEVICE;
                    break;
            }
            mBottomDeviceFilterDialog = new BottomDeviceFilterDialog(getContext(), BottomDeviceFilterDialog.TYPE_DEVICE, deviceCategory,"",deviceType) {
                @Override
                public void onConfirm(boolean hasFilter, List<DeviceBean> result) {
                    btnFilter.setSelected(hasFilter);
                    mManagerDeviceAdapter.setTotalData(result);
                    mManagerDeviceAdapter.checkAllSelect();
                }
            };
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .enableDrag(false)
                    .asCustom(mBottomDeviceFilterDialog);
        }
        mBottomDeviceFilterDialog.setInitCount(mManagerDeviceAdapter.getItemCount());
        List<FloorBean> floors = LLFloorDBManager.getInstance(getContext()).getNotEmptyRoomFloors();
        mBottomDeviceFilterDialog.setFloorBeans(floors);
        mBottomDeviceFilterDialog.show();
    }


    private void searchDevice(String keywords){
        if(allDevices != null){
            List<DeviceBean> searchDevices = new ArrayList<>();
            for(DeviceBean deviceBean : allDevices){
                if(deviceBean.getName() != null && deviceBean.getName().contains(keywords)){
                    searchDevices.add(deviceBean);
                }
            }
            mManagerDeviceAdapter.setTotalData(searchDevices);
        }
    }

    @Override
    protected void initData() {
        showDialog();
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                List<DeviceBean> devices = null;
                switch (type){
                    case TYPE_SELECT_TRIGGER_DEVICE:
                    case TYPE_SELECT_TRIGGER_DEVICE_NEW:
                        devices = LLDeviceDBManager.getInstance(getContext()).getTriggerDevices();
                        break;
                    case TYPE_SELECT_DEVICE_SHARE:
                        devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDevices();
                        break;
                    case TYPE_SELECT_SAME_DEVICE:
                        devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDevicesWithDeviceType(deviceType);
                        for(DeviceBean deviceBean : devices){
                            if(deviceBean.getDeviceSerialNo().equals(removeDeviceSerialNo)){
                                devices.remove(deviceBean);
                                break;
                            }
                        }
                        break;
                    case TYPE_PANEL_DEVICE:
                        devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDevicesWithType("wall_switch");
                        break;
                    default:
                        devices = LLDeviceDBManager.getInstance(getContext()).getAvailableDevices();
                        break;
                }
                emitter.onNext(devices);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        allDevices = devices;
                        mManagerDeviceAdapter.setTotalData(devices);
//                        selectArea.setText("全部设备" + " (" + devices.size() + ")");
                        hideDialog();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }

    private void loadSelectedDevices(){
        showDialog();
        Observable.create(new ObservableOnSubscribe<List<DeviceBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<DeviceBean>> emitter) throws Exception {
                List<DeviceBean> devices = mBottomDeviceFilterDialog.getAllDeviceFormSelectArea();
                emitter.onNext(devices);
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<DeviceBean>>() {
                    @Override
                    public void accept(List<DeviceBean> devices) throws Exception {
                        mManagerDeviceAdapter.setTotalData(devices);
                        mManagerDeviceAdapter.checkAllSelect();
                        hideDialog();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                    }
                });
    }



    private ManagerDeviceAdapter.SubClickListener createSubClickListener() {
        return new ManagerDeviceAdapter.SubClickListener() {
            @Override
            public void OntopicClickListener(boolean allSelect) {
                isAllSelect = allSelect;
                btnAllChoose.setSelected(allSelect);
            }

        };
    }
}